const canvas = document.querySelector("canvas");
const c = canvas.getContext("2d");

canvas.width = innerWidth;
canvas.height = innerHeight;

const scoreEl = document.querySelector("#scoreEl");
const startGameBtn = document.querySelector("#startGameBtn");
const modalEl = document.querySelector("#modalEl");
const bigScoreEl = document.querySelector("#bigScoreEl");
const liquidEl = document.getElementById("liquidEl");
const adImage = document.getElementById("adImage");
const adText = document.getElementById("adText");

const maxScore = 20000;
const friction = 0.99;

class Player {
	constructor(x, y, radius, color) {
		this.x = x;
		this.y = y;
		this.radius = radius;
		this.color = color;
	}

	draw() {
		c.beginPath();
		c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
		c.fillStyle = this.color;
		c.fill();
	}
}

class Projectile {
	constructor(x, y, radius, color, velocity) {
		this.x = x;
		this.y = y;
		this.radius = radius;
		this.color = color;
		this.velocity = velocity;
	}

	draw() {
		c.beginPath();
		c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
		c.fillStyle = this.color;
		c.fill();
	}

	update() {
		this.draw();
		this.x = this.x + this.velocity.x;
		this.y = this.y + this.velocity.y;
	}
}

class Enemy {
	constructor(x, y, radius, color, velocity) {
		this.x = x;
		this.y = y;
		this.radius = radius;
		this.color = color;
		this.velocity = velocity;
	}

	draw() {
		c.beginPath();
		c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
		c.fillStyle = this.color;
		c.fill();
	}

	update() {
		this.draw();
		this.x = this.x + this.velocity.x;
		this.y = this.y + this.velocity.y;
	}
}

class Particle {
	constructor(x, y, radius, color, velocity) {
		this.x = x;
		this.y = y;
		this.radius = radius;
		this.color = color;
		this.velocity = velocity;
		this.alpha = 1;
	}

	draw() {
		c.save();
		c.globalAlpha = this.alpha;
		c.beginPath();
		c.arc(this.x, this.y, this.radius, 0, Math.PI * 2, false);
		c.fillStyle = this.color;
		c.fill();
		c.restore();
	}

	update() {
		this.draw();
		this.velocity.x *= friction;
		this.velocity.y *= friction;
		this.x = this.x + this.velocity.x;
		this.y = this.y + this.velocity.y;
		this.alpha -= 0.01;
	}
}
const x = canvas.width / 2;
const y = canvas.height / 2;

let player = new Player(x, y, 10, "white");
let projectiles = [];
let enemies = [];
let particles = [];

// 在重新定义 canvas 大小时也重新设置游戏状态
function resizeCanvas() {
	canvas.width = innerWidth;
	canvas.height = innerHeight;
	player = new Player(canvas.width / 2, canvas.height / 2, 10, "white");
}
addEventListener("resize", resizeCanvas);

resizeCanvas(); // 确保初始化设置正确的尺寸
function init() {
	player = new Player(x, y, 10, "white");
	projectiles = [];
	enemies = [];
	particles = [];
	score = 0;
	scoreEl.innerHTML = score;

	liquidEl.style.height = (score / maxScore) * 100 + "%";
	bigScoreEl.innerHTML = score;
}

function spawnEnemies() {
	setInterval(() => {
		const radius = Math.random() * (30 - 4) + 4;

		let x;
		let y;
		if (Math.random() < 0.5) {
			x = Math.random() < 0.5 ? 0 - radius : canvas.width + radius;

			y = Math.random() * canvas.height;
		} else {
			x = Math.random() * canvas.width;
			y = Math.random() < 0.5 ? 0 - radius : canvas.height + radius;
		}

		const color = `hsl(${Math.random() * 360}, 50%, 50%)`;
		const angle = Math.atan2(canvas.height / 2 - y, canvas.width / 2 - x);
		const velocity = {
			x: Math.cos(angle),
			y: Math.sin(angle),
		};
		enemies.push(new Enemy(x, y, radius, color, velocity));
	}, 1000);
}
function updateAdvertisement(score) {
	// 根据分数定义不同的图片路径和广告语
	let imagePath = "";
	let adCopy = "";

	// 为每个分数区间定义图片和广告语
	if (score < 500) {
		imagePath = "images/wahaha1.png";
		adCopy = "加油！来瓶娃哈哈提提神！";
	} else if (score < 2000) {
		imagePath = "images/wahaha2.png";
		adCopy = "再接再厉！娃哈哈助你一臂之力！";
	} else if (score < 4000) {
		imagePath = "images/wahaha3.png";
		adCopy = "力量加满！娃哈哈，你的理想能量！";
	} else if (score < 6000) {
		imagePath = "images/wahaha4.png";
		adCopy = "精力全开！娃哈哈，让你活力四射！";
	} else if (score < 8000) {
		imagePath = "images/wahaha5.png";
		adCopy = "不错哦！来瓶娃哈哈庆祝一下！";
	} else if (score < 10000) {
		imagePath = "images/wahaha6.jpg";
		adCopy = "精彩纷呈！跟着娃哈哈一起冒险！";
	} else if (score < 12000) {
		imagePath = "images/wahaha7.jpg";
		adCopy = "全速前进！娃哈哈，速度与激情的伴侣！";
	} else if (score < 14000) {
		imagePath = "images/wahaha8.png";
		adCopy = "高分在望！娃哈哈，激励你的每一步！";
	} else {
		imagePath = "images/wahaha9.png";
		adCopy = "高分达成！这瓶娃哈哈奖励给你！";
	}

	// 设置图片源和广告文本
	adImage.src = imagePath;
	adText.textContent = adCopy;
}

let animationId;
let score = 0;

function animate() {
	animationId = requestAnimationFrame(animate);
	c.fillStyle = "rgba(0, 0, 0, 0.1)";
	c.fillRect(0, 0, canvas.width, canvas.height);
	player.draw();

	particles.forEach((particle, index) => {
		if (particle.alpha <= 0) {
			particles.splice(index, 1);
		} else {
			particle.update();
		}
	});

	projectiles.forEach((projectile, index) => {
		projectile.update();

		// 移除超出屏幕的子弹
		if (
			projectile.x + projectile.radius < 0 ||
			projectile.x + projectile.radius > canvas.width ||
			projectile.y + projectile.radius < 0 ||
			projectile.y + projectile.radius > canvas.height
		) {
			setTimeout(() => {
				projectiles.splice(index, 1);
			}, 0);
		}
	});

	enemies.forEach((enemy, index) => {
		enemy.update();
		const dist = Math.hypot(player.x - enemy.x, player.y - enemy.y);
		// 结束游戏
		if (dist - enemy.radius - player.radius < 1) {
			cancelAnimationFrame(animationId);
			modalEl.style.display = "flex";
			bigScoreEl.innerHTML = score;

			// 更新广告
			updateAdvertisement(score);
		}

		projectiles.forEach((projectile, projectileIndex) => {
			const dist = Math.hypot(
				projectile.x - enemy.x,
				projectile.y - enemy.y
			);

			// 当子弹和敌人相撞时
			if (dist - enemy.radius - projectile.radius < 1) {
				for (let i = 0; i < enemy.radius * 2; i++) {
					particles.push(
						new Particle(
							projectile.x,
							projectile.y,
							Math.random() * 2,
							enemy.color,
							{
								x: (Math.random() - 0.5) * (Math.random() * 6),
								y: (Math.random() - 0.5) * (Math.random() * 6),
							}
						)
					);
				}

				if (enemy.radius - 10 > 5) {
					// 增加分数
					score += 100;
					scoreEl.innerHTML = score;

					liquidEl.style.height = (score / maxScore) * 100 + "%";
					gsap.to(enemy, {
						radius: enemy.radius - 10,
					});
					setTimeout(() => {
						projectiles.splice(projectileIndex, 1);
					}, 0);
				} else {
					score += 250;
					scoreEl.innerHTML = score;

					liquidEl.style.height = (score / maxScore) * 100 + "%";
					// 移除敌人
					setTimeout(() => {
						enemies.splice(index, 1);
						projectiles.splice(projectileIndex, 1);
					}, 0);
				}
			}
		});
	});
}

// 发射子弹的共用函数
function shoot(event) {
	const rect = canvas.getBoundingClientRect();
	const root = document.documentElement;
	const x = event.clientX - rect.left - root.scrollLeft;
	const y = event.clientY - rect.top - root.scrollTop;
	const angle = Math.atan2(y - canvas.height / 2, x - canvas.width / 2);
	const velocity = {
		x: Math.cos(angle) * 5,
		y: Math.sin(angle) * 5,
	};
	projectiles.push(
		new Projectile(
			canvas.width / 2,
			canvas.height / 2,
			5,
			"white",
			velocity
		)
	);
}

// 为 canvas 添加鼠标点击事件，适配 PC 端
addEventListener("click", shoot);

// 为 canvas 添加触摸开始事件，适配移动端
addEventListener(
	"touchstart",
	function (event) {
		event.preventDefault();
		shoot(event.touches[0]); // 调用 shoot 函数，并传入触摸信息
	},
	{ passive: false }
);

// 用于重新开始游戏的函数，适配 PC 端
startGameBtn.addEventListener("click", () => {
	init();
	animate();
	modalEl.style.display = "none";
});

// 触摸开始事件
startGameBtn.addEventListener(
	"touchstart",
	event => {
		event.preventDefault();
		startGameBtn.style.backgroundColor = "#3b76c9"; // 更深的蓝色
		startGameBtn.style.transform = "scale(0.95)"; // 轻微缩小
	},
	{
		passive: false,
	}
);

// 触摸结束事件
startGameBtn.addEventListener(
	"touchend",
	event => {
		event.preventDefault();
		init();
		animate();
		startGameBtn.style.backgroundColor = "#4183d7"; // 恢复悬停时的颜色
		startGameBtn.style.transform = "scale(1.05)"; // 恢复放大效果
		modalEl.style.display = "none";
	},
	{
		passive: false,
	}
);

spawnEnemies();

addEventListener(
	"touchmove",
	function (event) {
		if (event.scale !== 1) {
			event.preventDefault();
		}
	},
	{ passive: false }
);
